package com.dyw.crashcatch;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

public class JavaCrash implements Thread.UncaughtExceptionHandler {

    private static Thread.UncaughtExceptionHandler defaultUncaughtExceptionHandler;
    private static String crashPath;

    private JavaCrash() {

    }

    public static void init(String path) {
        crashPath = path;
        defaultUncaughtExceptionHandler = Thread.getDefaultUncaughtExceptionHandler();
        Thread.setDefaultUncaughtExceptionHandler(new JavaCrash());
    }

    @Override
    public void uncaughtException(Thread t, Throwable e) {
        File dir = new File(crashPath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        long crashName = System.currentTimeMillis();
        File file = new File(dir, crashName + ".txt");

        try {
            PrintWriter pw = new PrintWriter(new FileWriter(file));
            pw.println("thread: " + t.getName());
            e.printStackTrace(pw);
            pw.flush();
            pw.close();
        } catch (IOException ioException) {
            ioException.printStackTrace();
        } finally {
            if (defaultUncaughtExceptionHandler != null) {
                defaultUncaughtExceptionHandler.uncaughtException(t, e);
            }
        }
    }
}
